package uk.ac.cam.echo.security;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import uk.ac.cam.echo.messages.Message;

/**
 * @author Tom Smith
 */
public class Reader implements Runnable {

	private final Socket m_Sock;
	private final int TIMEOUT = 30;	// Timeout to wait in seconds.

	private Message m_RFIDTagMessage;

	public Reader(Socket sock) {
		this.m_Sock = sock;
	}

	@Override
	public void run() {
		try {
			ObjectInputStream objectInputStream = new ObjectInputStream(this.m_Sock.getInputStream());

			while (true) {
				readMessage((Message) objectInputStream.readObject());
			}

		} catch (IOException e) {
			System.err.println("Server has ended the connection.");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

	/**
	 * Reads and acts on a message from the server.
	 * @param m The message to read.
	 */
	private synchronized void readMessage(Message m) {
			this.m_RFIDTagMessage = m;
			this.notify();
	}

	/**
	 * Get a Message relating to the RFID tag scanned.
	 * @return A UserMessage, LocationMessage or SecurityMessage, depending on the type.
	 * @throws InterruptedException
	 */
	public synchronized Message getMessage() throws InterruptedException {
		/*
		 *  We wait to get back a Message from the server, after sending an RFIDMessage.
		 */
		this.wait(TIMEOUT * 1000);
		return this.m_RFIDTagMessage;
	}

}
